package com.example.shiwu;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.chaquo.python.PyObject;
import com.chaquo.python.Python;
import com.chaquo.python.android.AndroidPlatform;
import com.example.shiwu.adapter.CheckAllAdapter;
import com.example.shiwu.db.dao.DeviceDao;
import com.example.shiwu.db.model.Arrange;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.ReceiveVolEle;
import com.example.shiwu.db.model.Sends;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.manager.DatabaseHelper;
import com.example.shiwu.service.ArrangeService;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.ReceiveService;
import com.example.shiwu.service.ReceiveVolEleService;
import com.example.shiwu.service.SendsService;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.StringToAscii;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.base.Joiner;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.SystemPropsUtil;

public class SendReceiveAddActivity extends AppCompatActivity {
    private RefreshLayout mRefreshLayout;
    private ListView listView;
    private CheckBox checkBox;
    private CheckAllAdapter myAdapter;
    private DeviceService deviceService;
    private ItemsService itemsService;
    private ReceiveService receiveService;
    private Map<String, Object> showitem;
    private List<Map<String, Object>> listitem;
    private ArrayList<Device> deviceLisAll = new ArrayList<Device>();

    private int currentPage = 0;
    private int pageSize = 2;
    private int totalSize = 0;
    public ListView editSb;
    public TextView title_text, title_seting, send_sub_btn;
    public ImageView title_back;
    private boolean checkSta = false;
    private DatabaseHelper dbHelper;
    private DeviceDao deviceDao;
    private Context myContext;
    private TextView pop_close;
    private EditText send_voltage_val, send_repeat_val, send_frequency_val, send_duration_val,
            send_point_a_val, send_point_b_val, send_point_m_val, send_point_n_val, clear_all_mux_box_connect_val;
    private PopupWindow mPopWindow;
    private SendsService sendsService;
    private ArrangeService arrangeService;
//    private TextView pop_close;

    private final String TAG = "SendReceiveActivity";
    public Socket mSocket;
    private final int DEFAULT_PORT = 8086;
    private String mIpAddress = ContextVariable.IP; //服务端ip地址
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private static final String IP_ADDRESS = "ip_address";
    private static final String CLIENT_PORT = "client_port";
    private static final String CLIENT_MESSAGETXT = "client_msgtxt";

    private OutputStream mOutStream;
    private InputStream mInStream;
    private SocketConnectThread mConnectThread;
    private SocketReceiveThread mReceiveThread;

    private HandlerThread mHandlerThread;
    //子线程中的Handler实例。
    private Handler mSubThreadHandler;

    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private int mSocketConnectState = STATE_DISCONNECTED;

    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_SEND_DATA = 6;
    private static final int MSG_SEND_DATA_BYTE = 7;
    private static final int MSG_RECEIVE_TU_DATA = 8;
    private static final int MSG_RECEIVE_TU_NEW_DATA = 9;
    private static final int MSG_RECEIVE_POP_DATA = 10;

    private static final int MSG_SEND_DATA_BYTE_RECEIVE = 1;//硬件成功返回信息
    private TextView receive_voltage;
    private Python py;
    private PyObject pyobj, pyobj1, pyplot,pyobj2,pyobj3;
    private byte[] bytesData;

    private Integer one_over = 0;
    private Integer header_count = 0;//总数据的头数
    private Integer error_count = 0;//总错误数据数
    private String correct = "";
    private String simpleUUID = "";
    private Integer machine = -1;
    private Integer cmd_id = null;
    private Integer status = 0;
    private Integer count = 0;
    private Integer header = 0;
    private Integer rec_count = 0;
    private Integer packet_indx = 0;
    private Integer old_packet_lens = 0;
    private Integer packet_lens = 0;//总包数 1536倒计数到0 packet_lens=0, bak_packet_lens=512, rec_count=512 self.send("kConfirm",rec_count)
    private Integer bak_packet_lens = 0; //1536倒计数 bak_packet_lens=512, rec_count=512 self.send("kConfirm",rec_count)

    private int receive_count = 0;//用与截取0，success;10,1,10;的标识
    public int length_byte = 0;//合并Byte
    private String no_id_str = "";//不包含数据头 10.1024,12
    public byte[] all_byte;
    public byte[] all_byte_de_weight; //去/,后的byte[]
    public String receiveDataAll = "";
    public ArrayList<byte[]> all_byte_lis;
    public int count_byte = 0;
    public int byte_len = 0;
    private String cmd_index_len = "";//消息的id 10
    private boolean next_sta = false;
    private boolean byte_sta = false;//组装数据用，完全组装后 true
    private View contentView;
    private String tx_voltage = "";//发送电压
    private String tx_current = "";//发射电流
    private String rx_voltage = "";//接受电压
    private ImageView mChart1;
    private String strData;//接收总数据数据，拼接完整数据后再解析
    private StringBuffer stringBufferData;//接收总数据数据，拼接完整数据后再解析

    private Boolean bl = false;
    private Boolean bl1 = false;
    private Boolean bl2 = false;
    private Boolean bl3 = false;
    private Boolean bl4 = false;
    private Boolean bool = false;
    private int header_cou = 0;
    private int loding_count = 0;
    private String sta = "";
    private int success_count = 0;
    private int receive_packet_indx_count = 0;
    private Boolean bool1 = true;
    private int abmn_indx = 0;

    private ReceiveVolEleService receiveVolEleService;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;
                case MSG_SOCKET_CONNECT:
                    mSocketConnectState = STATE_CONNECTED;
                    System.out.println(R.string.disconnect);
                    mReceiveThread = new SocketReceiveThread();
                    mReceiveThread.start();
                    break;
                case MSG_SOCKET_DISCONNECT:
                    System.out.println(R.string.connect);
                    mSocketConnectState = STATE_DISCONNECTED;
                    closeConnection();
                    break;
                case MSG_SOCKET_CONNECTFAIL:
                    mSocketConnectState = STATE_DISCONNECTED;
                    System.out.println("======================连接失败=========================");
                    break;
                case MSG_RECEIVE_DATA:
                    break;
                case MSG_RECEIVE_TU_DATA://采集数据展示图形
                    //生成的是不带-的字符串，类似于：b17f24ff026d40949c85a24f4f375d42
                    //String simpleUUID = IdUtil.simpleUUID();
                    Map<String, byte[]> obj1 = (Map<String, byte[]>) msg.obj;
                    byte[] ios = obj1.get("ios");
                    mChart1.setImageBitmap(BitmapFactory.decodeByteArray(ios, 0, ios.length));
//                    savebitmap(BitmapFactory.decodeByteArray(ios, 0, ios.length));//存储图片

                    String vol_ele = new String(obj1.get("vol_ele"));
                    String[] vel = vol_ele.split(";");
                    saveFile(vel,simpleUUID);
                    List<ReceiveVolEle> lis = new ArrayList<ReceiveVolEle>();
                    ReceiveVolEle rve = null;
                    MyQueue queue = new MyQueue();
                    for (int i = 1; i < vel.length; i++) {
                        String vel_new = "";
//                        if (i != 0) {
//                            vel_new = vel[i].substring(1, vel[i].length());
//                        } else {
                            vel_new = vel[i];
                        //}
                        if (!vel_new.equals("")) {
                            String[] vel_new_lis = vel_new.split(",");
                            rve = new ReceiveVolEle();
                            for (int j = 0; j < vel_new_lis.length; j++) {
                                switch (j) {
                                    case 2:
                                        rve.setIndx(Integer.parseInt(vel_new_lis[j]));
                                        rve.setCreateTime(DateUtils.parseDate());
                                        rve.setGropId(simpleUUID);
                                        Items items = findSelectItem();
                                        rve.setItemId(items.getId());
                                        break;
                                    case 8:
                                        rve.setTxv(vel_new_lis[j]);
                                        break;
                                    case 9:
                                        rve.setTxc(vel_new_lis[j]);
                                        break;

                                    case 10:
                                        rve.setRxv(vel_new_lis[j]);
                                        break;
                                }

                            }
                            lis.add(rve);
                            queue.enQueue(rve);
                            ReceiveVolEle rveDo = (ReceiveVolEle) queue.deQueue();
                            //queue.clear();
                            receiveVolEleService.save(rveDo);
                        }

                    }

                    System.out.println("---- thread =" + mConnectThread);
                    //setImageVal(rx_voltage);
                    break;
                case MSG_RECEIVE_TU_NEW_DATA:
                    byte[] data4 = pyobj1.callAttr("onKConfirmToMcu",rec_count).toJava(byte[].class);
                    sendByte(data4);
                    break;
                case MSG_RECEIVE_POP_DATA:
                    Boolean bool = showPopupWindow();
//                    byte[] data6 = pyobj1.callAttr("onKConfirmToMcu",rec_count).toJava(byte[].class);
//                    sendByte(data6);
                    break;
                default:
                    break;
            }
        }

        ;
    };
    /**
     * 定义文件保存的方法，写入到文件中，所以是输出流
     */
    public void saveFile(String[] vel,String simpleUUID) {

        String content = "";
        FileOutputStream fos = null;
        try {
            // Context.MODE_PRIVATE私有权限，Context.MODE_APPEND追加写入到已有内容的后面
            fos = myContext.openFileOutput(getFileName(simpleUUID), Context.MODE_APPEND);
            String content1 = vel[0];
            if(!content1.equals("")&&content1.length()>0){
                fos.write(content1.getBytes());
                fos.write("\r\n".getBytes());//写入换行
            }

            for (int i = vel.length-1; i >=0; i--) {
                if(i>0){
                    content = vel[i].substring(1);
                    fos.write(content.getBytes());
                    fos.write("\r\n".getBytes());//写入换行
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * get file name such as 20171031.txt
     *
     * @return
     */
    private String getFileName(String simpleUUID) {
        Items items = findSelectItem();
        return items.getId()+"-"+simpleUUID+ ".cvs";
    }
    private void savebitmap(Bitmap bitmap) {

        //创建文件，因为不存在2级目录，所以不用判断exist，要保存png，这里后缀就是png，要保存jpg，后缀就用jpg
        File file = new File(Environment.getExternalStorageDirectory() + "/mfw.png");
        try {
            //文件输出流
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            //压缩图片，如果要保存png，就用Bitmap.CompressFormat.PNG，要保存jpg就用Bitmap.CompressFormat.JPEG,质量是100%，表示不压缩
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            //写入，这里会卡顿，因为图片较大
            fileOutputStream.flush();
            //记得要关闭写入流
            fileOutputStream.close();
            //成功的提示，写入成功后，请在对应目录中找保存的图片
            //System.out.println("写入成功！目录" + Environment.getExternalStorageDirectory() + "/mfw.png");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            //失败的提示
            //System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/mfw.png");
        } catch (IOException e) {
            e.printStackTrace();
            //失败的提示
            //System.out.println("写入失败！目录" + Environment.getExternalStorageDirectory() + "/mfw.png");
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出HandlerThread的Looper循环。
        System.out.println("---------------------- onDestroy --------------------");
        mHandlerThread.quit();
        closeConnection();
    }

    class SocketConnectThread extends Thread {
        public void run() {
            try {
                //连接服务端，指定服务端ip地址和端口号。
                mSocket = new Socket(mIpAddress, mClientPort);
                mSocket.setKeepAlive(true);
                //mSocket.setSoTimeout(5000);  // 设置超时时间为 5 秒
                if (mSocket != null) {
                    //获取输出流、输入流
                    mOutStream = mSocket.getOutputStream();
                    mInStream = mSocket.getInputStream();

                }
            } catch (Exception e) {
                e.printStackTrace();
                mHandler.sendEmptyMessage(MSG_SOCKET_CONNECTFAIL);
                return;
            }
            Log.i(TAG, "connect success");
            //if(receive_packet_indx_count == 0){
                sendTxt("22,S;");
                mHandler.sendEmptyMessage(MSG_SOCKET_CONNECT);
//            }else{
//                byte[] data4 = pyobj1.callAttr("onKConfirmToMcu",128).toJava(byte[].class);
//                sendByte(data4);
//            }

        }

    }

    class SocketReceiveThread extends Thread {
        private final Object lock = new Object();
        private boolean threadExit;

        public SocketReceiveThread() {
            threadExit = false;
        }

        /**
         * 调用这个方法实现暂停线程
         */
        void pauseThread() {
            threadExit = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        void resumeThread() {
            threadExit = false;
            //startPause = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        void onPause() {
            synchronized (lock) {
                try {
//                    editor.clear().putBoolean("first_stop", false);
//                    editor.commit();
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void run() {
           // Log.i(TAG, "read buffer threadExit = "+threadExit);
            while (threadExit == false) {
                //Log.i(TAG, "read buffer loding_count= "+loding_count);
                if (loding_count != 0) {
                    try {
                        byte[] buffer = new byte[1];
                        //Log.i(TAG, "read buffer = "+mInStream);
                        //Log.i(TAG, "read buffer mReceiveThread = "+mReceiveThread.getName());
                        //Log.i(TAG, "read buffer mConnectThread = "+mConnectThread.getName());


                        if(receive_packet_indx_count !=0){

                        }else{
                            Thread.sleep(5);
                        }

//                        Log.i(TAG, "read buffer mInStream = "+mInStream.read(buffer));
//                        System.out.println(mReceiveThread.getState());
                        //this.resumeThread();

                        //读取数据，返回值表示读到的数据长度。-1表示结束
                        int count = mInStream.read(buffer);
                       // Log.i(TAG, "read buffer 11111111111111111111111111 "+count);
                        count_byte = count;
                        if (count == -1) {
                            Log.i(TAG, "read read -1");
                            mHandler.sendEmptyMessage(MSG_SOCKET_DISCONNECT);
                            break;
                        } else {
                            //System.out.println("---- buffer = "+buffer);
                            if (success_count <= 4) {
                                int obj = DataParseUtil.EntiretyDecodeStructByteHeader(buffer, header_cou);//过滤header
                                //System.out.println("---obj11111 =" + obj);
                                if (obj == 1) {
                                    header_cou = obj;
                                }
                                if (obj == 2) {
                                    header_cou = 0;
                                    success_count += 1;
                                }
                            } else if (success_count == 5) {
                                header_cou = 1;
                                int obj = DataParseUtil.EntiretyDecodeStructByteHeader(buffer, header_cou);//过滤header
                                String receiveData = new String(buffer, "iso8859-1");
                                receiveDataAll += receiveData;

                                //System.out.println("---obj2 =" + obj);
                                if (obj == 2) {
                                    header_cou = 0;
                                    success_count += 1;
                                }
                                if (success_count == 6) {
                                    cmd_index_len = DataParseUtil.getDataForHeaderIndex(receiveDataAll);
                                    //packet_indx = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[1]));
                                    packet_lens = Integer.valueOf(DataParseUtil.initPython(cmd_index_len.split(",")[2]));
                                    DataParseUtil.setPageLens(packet_lens);
                                }
                            } else {
                                if (success_count == 6) {
                                    success_count += 1;
                                    continue;
                                }
                                if (success_count > 6) {
                                    DataParseUtil.entiretyDecodeStructByte(buffer);

                                }
                            }
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        void threadExit() {
            threadExit = true;
        }
    }

    private void initHandlerThraed() {
        //创建HandlerThread实例
        mHandlerThread = new HandlerThread("handler_thread");
        //开始运行线程
        mHandlerThread.start();
        //获取HandlerThread线程中的Looper实例
        Looper loop = mHandlerThread.getLooper();
        //创建Handler与该线程绑定。
        mSubThreadHandler = new Handler(loop) {
            public void handleMessage(Message msg) {
                Log.i(TAG, "mSubThreadHandler handleMessage thread:" + Thread.currentThread());
                switch (msg.what) {
                    case MSG_SEND_DATA:
                        writeMsg((String) msg.obj);
                        break;
                    case MSG_SEND_DATA_BYTE:
                        writeMsgByte((byte[]) msg.obj);
                    default:
                        break;
                }
            }

            ;
        };
    }

    private void set() {
        View setview = LayoutInflater.from(this).inflate(R.layout.dialog_clientset, null);
        final EditText ipAddress = (EditText) setview.findViewById(R.id.edtt_ipaddress);
        final EditText editport = (EditText) setview.findViewById(R.id.client_port);
        Button ensureBtn = (Button) setview.findViewById(R.id.client_ok);

        ipAddress.setText(mSharedPreferences.getString(IP_ADDRESS, null));
        editport.setText(mSharedPreferences.getInt(CLIENT_PORT, 8086) + "");

        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(setview); //设置dialog显示一个view
        final AlertDialog dialog = builder.show(); //dialog显示
        ensureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String port = editport.getText().toString();
                mIpAddress = ipAddress.getText().toString();
                if (port != null && port.length() > 0) {
                    mClientPort = Integer.parseInt(port);
                }
                SharedPreferences.Editor editor = mSharedPreferences.edit();
                editor.putString(IP_ADDRESS, mIpAddress);
                editor.putInt(CLIENT_PORT, mClientPort);
                editor.commit();
                dialog.dismiss(); //dialog消失
            }
        });

    }

    private void startConnect() {
        Log.i(TAG, "startConnect");
        if (mIpAddress == null || mIpAddress.length() == 0) {
            Looper.prepare();
            Toast.makeText(this, "请设置ip地址", Toast.LENGTH_LONG).show();
            Looper.loop();
            return;
        }
        if (mSocketConnectState != STATE_DISCONNECTED) return;
        mConnectThread = new SocketConnectThread();
        mConnectThread.start();
        mSocketConnectState = STATE_CONNECTING;
        Log.i(TAG, "startConnectSocket");
    }

    private void sendTxt(String str) {
        if (mSocket == null) {
            Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show();
            return;
        }
        if (str.length() == 0)
            return;
        Message msg = new Message();
        msg.what = MSG_SEND_DATA;
        msg.obj = str;
        mSubThreadHandler.sendMessage(msg);
    }

    private void sendByte(byte[] str) {
        System.out.println("---------------------------------str----------------------------------------" + str);
        if (mSocket == null) {
            Toast.makeText(this, "没有连接", Toast.LENGTH_SHORT).show();
            return;
        }
        if (str.length == 0)
            return;

        Message msg = new Message();
        msg.what = MSG_SEND_DATA_BYTE;
        msg.obj = str;
        msg.arg1 = MSG_SEND_DATA_BYTE_RECEIVE;//1 为硬件成功返回数据 弹出图表
        mSubThreadHandler.sendMessage(msg);
    }

    private void writeMsg(String msg) {
        Log.i(TAG, "writeMsg msg=" + msg);
        if (msg.length() == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg.getBytes());//发送
            mOutStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void writeMsgByte(byte[] msg) {
        Log.i(TAG, "------------------------------------------------writeMsgByte msg=" + msg);
        if (msg.length == 0 || mOutStream == null)
            return;
        try {
            mOutStream.write(msg);//发送
            mOutStream.flush();
            Log.i(TAG, "------------------------------------------------writeMsgByte mOutStream.flush");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void closeConnection() {
        try {
            if (mOutStream != null) {
                mOutStream.close(); //关闭输出流
                mOutStream = null;
            }
            if (mInStream != null) {
                mInStream.close(); //关闭输入流
                mInStream = null;
            }
            if (mSocket != null) {
                mSocket.close();  //关闭socket
                mSocket = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (mReceiveThread != null) {
            mReceiveThread.threadExit();
            mReceiveThread = null;
        }
        mSocketConnectState = STATE_DISCONNECTED;
    }


    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.send_receive_add);
        Log.i(TAG, "mInStream = "+mInStream);

        mSocket = null;
        mHandlerThread = null;
        arrangeService = new ArrangeService();
        myContext = this;
        deviceDao = new DeviceDao();
        all_byte_lis = new ArrayList<byte[]>();
        stringBufferData = new StringBuffer();
        title_back = findViewById(R.id.title_back);
        title_text = findViewById(R.id.title_text);
        title_seting = findViewById(R.id.title_setting);
        title_text.setText("发射接收信息");
        title_seting.setVisibility(View.INVISIBLE);
        receive_voltage = findViewById(R.id.receive_voltage_val);

        send_sub_btn = findViewById(R.id.send_sub_btn);
        receiveService = new ReceiveService();
        deviceService = new DeviceService();
        itemsService = new ItemsService();
        listitem = new ArrayList<Map<String, Object>>();
        SharedPreferences sp = this.getSharedPreferences(this.getPackageName(), Activity.MODE_PRIVATE);
        String ips = sp.getString("ip", "");
        initTextView();
        initData();
        startConnect();
        initHandlerThraed();//启动socket


//        if (mSocketConnectState == STATE_CONNECTED) {
//            closeConnection();
//        } else {
//
//            startConnect();
//        }
        mSharedPreferences = getSharedPreferences("setting", Context.MODE_PRIVATE);
        //获取保存的ip地址、客户端端口号
        //mIpAddress = mSharedPreferences.getString(IP_ADDRESS, null);
        //mClientPort = mSharedPreferences.getInt(CLIENT_PORT, DEFAULT_PORT);
        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SendReceiveAddActivity.this.finish();
            }
        });

        send_sub_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (send_voltage_val.length() > 0 &&
                        send_frequency_val.length() > 0 &&
                        send_duration_val.length() > 0) {
                    getText();
                } else {
                    Toast.makeText(myContext, "发射信息不能为空！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        try {
            initPython(this);
            //pyMain();
        } catch (JSONException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    private void pyMain(){
        pyobj2.callAttr("_initSocket1",mIpAddress);
    }

    private void initTextView() {
        send_voltage_val = findViewById(R.id.send_voltage_val);
        send_repeat_val = findViewById(R.id.send_repeat_val);
        send_frequency_val = findViewById(R.id.send_frequency_val);
        send_duration_val = findViewById(R.id.send_duration_val);
//        send_point_a_val = findViewById(R.id.send_point_a_val);
//        send_point_b_val = findViewById(R.id.send_point_b_val);
//        send_point_m_val = findViewById(R.id.send_point_m_val);
//        send_point_n_val = findViewById(R.id.send_point_n_val);
        clear_all_mux_box_connect_val = findViewById(R.id.clear_all_mux_box_connect_val);
    }

    private void getText() {
        System.out.println("============================mReceiveThread==========================="+mReceiveThread.getName());

        int packet_indx1 = Integer.parseInt(String.valueOf(send_repeat_val.getText()));
        packet_indx = packet_indx1;
        Sends sends = new Sends();
        sends.setVoltage(String.valueOf(send_voltage_val.getText()));
        sends.setType(0);
        sends.setStatus(0);
        sends.setRepeatNum(String.valueOf(send_repeat_val.getText()));
        sends.setSendFrequency(String.valueOf(send_frequency_val.getText()));
        sends.setSendDuration(String.valueOf(send_duration_val.getText()));

        Items items = findSelectItem();
        sends.setItemId(items.getId());
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = new Date(System.currentTimeMillis());
        sends.setCreateTime(sim.format(date));
        sends.setUpdateTime(sim.format(date));
        simpleUUID = IdUtil.simpleUUID();
        sends.setUid(simpleUUID);
        sendsService = new SendsService();
        receiveVolEleService = new ReceiveVolEleService();
        String clearStr = clear_all_mux_box_connect_val.getText().toString();
        String[] clearStrLis = clearStr.split(",");
        int cslen = clearStrLis.length;
        int csnewlen = 10 - clearStrLis.length;
        String[] clearStrLisNew = new String[csnewlen];
        List<String> list = null;
        if (clearStrLis.length > 0 && clearStrLis.length < 10) {

            for (int i = 0; i < csnewlen; i++) {
                clearStrLisNew[i] = String.valueOf(0);
            }
            list = new ArrayList(Arrays.asList(clearStrLis));
            list.addAll(Arrays.asList(clearStrLisNew));
        } else {
            list = new ArrayList(Arrays.asList(clearStrLis));
        }
        String join2 = Joiner.on(",").join(list);
        sends.setBoxaddr(join2);
        Object[] c = list.toArray();
        String[] clearStrLisAll = Arrays.toString(c).replace("[", "").replace("]", "").split(",");
        Arrange arrange1 = new Arrange();
        arrange1.setItemId(items.getId());
        List<Arrange> arrangeLis = arrangeService.getArrange(arrange1);
        Integer ns = 0;
        String dtype,shape,abmn;
        if(arrangeLis.size()==0){
            Toast.makeText(myContext, "请先添加排列设计！", Toast.LENGTH_SHORT).show();
            return;
        }else {
            ns = arrangeLis.get(0).getDeviceTypeLen();
            dtype = arrangeLis.get(0).getDtype();
            shape = arrangeLis.get(0).getShape();
            abmn = arrangeLis.get(0).getDeviceTypeVal();
        }


        int countItem = findItemCount();

        if (countItem > 0) {
//            int sendCount = findSendCount();
//            System.out.println("======== sendCount ========"+sendCount);
//            if (sendCount > 0) {
                //boolean bl = sendsService.updade(sends, new Sends());
                boolean bl = sendsService.save(sends);
                if (bl) {
                    Toast.makeText(myContext, "保存成功！", Toast.LENGTH_SHORT).show();
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    editor.putInt("header_count", 0);
                    editor.remove("header");// 初始化清空header
                    editor.commit();

//                    Message msg = new Message();
//                    msg.what = MSG_RECEIVE_POP_DATA;
//                    mHandler.sendMessage(msg);
                    showPopupWindow();

//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
                        //for (int i = 0; i < ns; i++) {


                        while (bool1) {
                            String abmnStr = pyobj1.callAttr("subABMN", abmn, dtype, shape, abmn_indx).toJava(String.class);
                            String[] abmnlis = null;
                            if (abmnStr.length() > 0) {
                                abmnlis = abmnStr.split(",");
                            }
                            //kSetTxWaveWithParam 3
                            byte[] data = pyobj1.callAttr("onSendParamToMcu", "1", send_frequency_val.getText().toString(), packet_indx1, send_voltage_val.getText().toString()).toJava(byte[].class);
                            sendByte(data);
                            //kClearAllMuxBoxConnect 15
                            byte[] data2 = pyobj1.callAttr("clear_mux", clearStrLisAll[0], clearStrLisAll[1], clearStrLisAll[2], clearStrLisAll[3], clearStrLisAll[4],
                                    clearStrLisAll[5], clearStrLisAll[6], clearStrLisAll[7], clearStrLisAll[8], clearStrLisAll[9]).toJava(byte[].class);
                            sendByte(data2);
                            //kSetMuxBoxConnect 2
                            byte[] data3 = pyobj1.callAttr("update_poles_connect", 1 + "," + abmnlis[0], 1 + "," + abmnlis[1],
                                    1 + "," + abmnlis[2], 1 + "," + abmnlis[3]).toJava(byte[].class);
                            sendByte(data3);

                            try {
                                
                                Thread.sleep(1000);
                                loding_count = 1;
                                //sendTxt("4,start;");
                                pyobj3.callAttr("onStartSampleOnce");

//                                Map<String, byte[]> obj1 = DataParseUtil._recv_float_array_with_indx_new(String.valueOf(packet_indx1),abmnlis[0],abmnlis[1],abmnlis[2],abmnlis[3]);
//
//                                if (obj1.size() != 0) {
//
//                                    sta = new String(obj1.get("status"));
//                                    String rec_count = new String(obj1.get("rec_count"));
//
//                                    if (sta.equals("0")) {
//                                        receive_packet_indx_count+=1;
//                                        packet_indx--;
//                                        System.out.println("mIpAddress ========= "+mIpAddress);
////                                        new Thread(new Runnable() {
////                                            @Override
////                                            public void run() {
//                                                while (packet_indx > 0) {
//
//                                                    new Thread(new Runnable() {
//                                                        @Override
//                                                        public void run() {
//
//                                                            //                                                                mHandlerThread = null;
////                                                                mConnectThread = null;
////                                                                mReceiveThread = null;
////                                                                mReceiveThread = new SocketReceiveThread();
////                                                                mReceiveThread.start();
////                                                                mSocketConnectState = STATE_DISCONNECTED;
////                                                                startConnect();
////                                                                initHandlerThraed();//启动socket
////                                                                Thread.sleep(1000);
//                                                            //mHandler = null;
//                                                            mReceiveThread.threadExit= false;
//                                                            //System.out.println(mReceiveThread.isInterrupted());
//
//                                                           // System.out.println(mConnectThread.getState());
//                                                            mSocketConnectState = STATE_DISCONNECTED;
//
//
//                                                            mInStream = null;
//                                                            try {
//                                                                mInStream = mSocket.getInputStream();
//                                                                startConnect();
//
//                                                            } catch (IOException e) {
//                                                                throw new RuntimeException(e);
//                                                            }
//                                                            //System.out.println(mConnectThread.getState());
//
//                                                            //kPcConfirm 16
////                                                            byte[] data4 = pyobj1.callAttr("onKConfirmToMcu",rec_count).toJava(byte[].class);
////                                                            sendByte(data4);
//                                                            //System.out.println(mConnectThread.getName());
//                                                            //System.out.println(mReceiveThread.getState());
//
//
//                                                        }
//                                                    }).start();
//
//                                                    Message msg1 = new Message();
//                                                    msg1.what = MSG_RECEIVE_TU_DATA;
//                                                    msg1.obj = obj1;
//                                                    mHandler.sendMessage(msg1);
//                                                    packet_indx--;
//
//                                                    if(packet_indx ==0){
//                                                        bool1 = true;
//                                                        abmn_indx +=1;
//                                                    }else {
//                                                        bool1 = false;
//
//                                                    }
//                                                }
////                                            }
////                                        }).start();
//
//                                    }else {
//                                        Thread.sleep(1000);
//                                        byte[] data4 = pyobj1.callAttr("onKConfirmToMcu",0).toJava(byte[].class);
//                                        sendByte(data4);
//                                    }
//                                    bool1 = false;
//                                }

                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }

                        }
                        //}
//




//                    String ip = "192.168.4.1";
//                    byte[] data4 = pyobj.callAttr("onStartSampleOnce", ip).toJava(byte[].class);
//                    sendByte(data4);
                    rec_count = 0;
                    no_id_str = "";

                }
//            } else {
//                boolean bl = sendsService.save(sends);
//                if (bl) {
//                    initHandlerThraed();//启动socket
//                    startConnect();
//                    Toast.makeText(myContext, "保存成功！", Toast.LENGTH_SHORT).show();
//                    showPopupWindow();
//                }
//            }

        } else {
            Toast.makeText(myContext, "请先创建项目！", Toast.LENGTH_SHORT).show();

        }

    }

    private void initData() {

        Sends sends = new Sends();
        Items items = findSelectItem();
        //sends.setId(1);
        sends.setItemId(items.getId());
        sendsService = new SendsService();
        //sendsService.updade(sends,new Sends());
        List<Sends> sendlis = sendsService.getSendsLast(sends);
        if (sendlis.size() > 0) {
            send_voltage_val.setText(sendlis.get(0).getVoltage());
            //send_electric_val.setText(sendlis.get(0).getElectricity());
            send_repeat_val.setText(sendlis.get(0).getRepeatNum());
            send_frequency_val.setText(sendlis.get(0).getSendFrequency());
            send_duration_val.setText(sendlis.get(0).getSendDuration());
//            send_point_a_val.setText(sendlis.get(0).getPoleA());
//            send_point_b_val.setText(sendlis.get(0).getPoleB());
//            send_point_m_val.setText(sendlis.get(0).getPoleM());
//            send_point_n_val.setText(sendlis.get(0).getPoleN());
            clear_all_mux_box_connect_val.setText(sendlis.get(0).getBoxaddr());
        }
    }

    private Integer findSendCount() {
        Items items = findSelectItem();
        sendsService = new SendsService();
        List<Sends> lis = sendsService.getSends(new Sends(items.getId()));
        return lis.size();
    }

    private Integer findItemCount() {
        itemsService = new ItemsService();
        List<Items> lis = itemsService.getItems(new Items());
        return lis.size();
    }

    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            items1 = lis.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    /**
     * 保存后的弹框
     */
    private Boolean showPopupWindow() {

        //设置contentView
        contentView = LayoutInflater.from(myContext).inflate(R.layout.send_receive_add_pop, null);
        mPopWindow = new PopupWindow(contentView,
                ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        setAlpha(0.2f);
        mChart1 = contentView.findViewById(R.id.send_pop_chart);

        //显示PopupWindow
        View rootview = LayoutInflater.from(myContext).inflate(R.layout.send_receive_add, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
        //viewHolder.set
        pop_close = contentView.findViewById(R.id.send_pop_close);
        pop_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(myContext, "关闭 === " + v.getId(), Toast.LENGTH_SHORT).show();
                mPopWindow.dismiss();
                setAlpha(1.0f);
            }
        });

        //把背景还原
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1.0f);
            }
        });
//        CurveCharUtil curveCharUtil = new CurveCharUtil();
//        LineChart mChart1 = contentView.findViewById(R.id.send_pop_chart);
//        curveCharUtil.initChar(mChart1);
        return true;
    }

    private void setImageVal(String tx_voltage) {
        //final ViewHolder viewHolder;
        bytesData = null;
        bytesData = pyobj.callAttr("sendCurve", tx_voltage).toJava(byte[].class);
        mChart1.setImageBitmap(BitmapFactory.decodeByteArray(bytesData, 0, bytesData.length));
    }

    private void initPython(Context myContext) throws JSONException, InterruptedException {
        //初始化python环境
        if (!Python.isStarted()) {
            Python.start(new AndroidPlatform(myContext));
        }

        py = Python.getInstance();
        //调用hello_python.py里面的plot函式
        pyobj = py.getModule("plotmy");
        pyobj1 = py.getModule("Send_Param");
        pyobj2 = py.getModule("Struct_Data");
        pyobj3 = py.getModule("earth_main");

    }
//    private void initPython(Context myContext) throws JSONException, InterruptedException {
//        //初始化python环境
//        if (!Python.isStarted()) {
//            Python.start(new AndroidPlatform(myContext));
//        }
//
//        py = Python.getInstance();
//        pyobj = py.getModule("Send_Param");
//    }

    private void setAlpha(float f) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    public class ViewHolder {

        public ImageView mChart1;

        public ViewHolder(View view, int position) {
            mChart1 = view.findViewById(R.id.send_pop_chart);

        }

    }


}